<style lang="scss">
.orderInfon_main{
     .weui-cell__ft{
            color: #ff0000;
            font-size: 15px;
        }  
        .vux-cell-bd .vux-label{
            font-size:15px !important;
            color:#666;
        }
}
</style>

<style lang="scss" scoped>
.orderInfon_main_priceColl {
    margin: 10px 0 50px;
    .vux-x-textarea {
        height: auto;
    }
}
.orderInfon_main_defaultAddress{
    padding: 12px 15px;
    box-sizing: border-box;
    font-size: 15px;
    color: #333;
    background-color: #fff;
    border-bottom: 1px solid #dfdfdf;
    >span{
        color: #ff0000;        font-size: 15px;
        margin-left: 10px;
    }
}
.orderInfon {
    &_main {
        .weui-cell__ft{
            color: #ff0000;
            font-size: 16px;
        }
        
        height: calc(100% - 101px);
        box-sizing: border-box;
        overflow-y: auto;
        background-color: #f3f3f3;
        .weui-cells {
            margin: 0;
        }
        .weui-cell:before {
            left: 0;
        }
        .main_since_single {
            margin: 0;
            // border-top: 1px solid #eee;
        }
        &_address {
            background-color: #fff;
            .weui-cell {
                &:nth-of-type(1) {
                    height: 60px;
                }
                &:nth-of-type(2) {
                    height: 60px;
                }
            }
            .nodefault {
                height: 60px !important;
            }
        }
        &_timeRange {
            box-sizing: border-box;
            padding: 0 15px;
            height: 44px;
            line-height: 44px;
            color: #272727;
            font-size: 15px;
            background-color: #fff;
            margin-top: 10px;
            // margin-bottom: 0;
            display: flex;
            justify-content: space-between;
        }
        &_plan{
            height: 44px;
            margin-bottom: 15px;
            .weui-cell{
                padding: 12px 15px;
            }
            .weui-cells{
                &:after{
                    display: none;
                }
            }
        }
    }

    &_footer {
        z-index: 999;
        height: 50px;
        line-height: 50px;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: #fff;
        box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.1);
        display: flex;
        &_price{
            font-size: 18px;
            color: #333;
        }
        &_btn {
            font-size: 18px;
            color: #fff;
            line-height: 50px;
            width: 120px;
            text-align: center;
            height: 50px;
            background-color: #2196f3;
        }
        &_noControl{
           font-size: 18px;
            color: #fff;
            line-height: 50px;
            width: 150px;
            text-align: center;
            height: 50px;
            background-color: #a9a9a9; 
        }
    }
}
.bookMain_carContent_list{
    // margin-top: 10px;
}
.bookMain_carContent_single{
                height: 75px;
                box-sizing: border-box;
                background-color: #fff;
                padding: 7.5px 15px;
                display: flex;
                align-items: center;
                position: relative;
                border-top: 1px solid #dfdfdf;
                >img{
                    height: 60px;
                    width: 60px;
                    margin-right: 15px;
                }
                >i{
                  color: #666;
                  font-size: 16px;      
               }
                >h3{
                    font-size: 16px;
                    color: #666;
                    line-height: 20px;
                    flex-grow: 1;
                }
            }
.orderInfo_main_content {
    height: calc(100% - 107px);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}
</style>

<template lang="pug">
    div
        header-cop(:heder_title="title")
        div.orderInfon_main
            b-scroll(
                :data="localdata.data",
                pulldown=true,
                ref="scollView"
                    )
                div.orderInfo_main_content
                    h3.orderInfon_main_defaultAddress 配送地址
                        span {{service_area}}
                    group.orderInfon_main_address
                        //-- 用户收货地址 -->
                        cell(v-show="haveDefault" ,:title="getNamePhone",:link="{path:'/addressList?chose=1'}" ,:inline-desc='getAddress')
                        cell(v-show="!haveDefault", class="nodefault", title="请选择收货地址" ,:link="{path:'/addressList?chose=1'}")
                        //-- 选择物流方式 -->
                    //-- 订单列表 -->
                    ul.bookMain_carContent_list    
                        li(v-for="item,index in localdata.data").bookMain_carContent_single
                            img(@load="scollRefresh",:src="imgFormat(item.img_medium)")
                            h3.twonowarp {{item.title}}
                            i(@click="delItem(index)").iconfont &#xe618;
                    //-- 租赁时间 -->
                    div.orderInfon_main_timeRange 借阅时间：{{rentRange.start}}&nbsp;至&nbsp;{{rentRange.end}}
                        span 共1个月
                    group.orderInfon_main_plan
                        cell(title="选择会员计划",
                        is-link,
                        :link="'/mine_plan?choose=1&&num='+localdata.data.length",
                        :value="choosePlan.name ? choosePlan.name : planCount + '张可选'"
                        )
                    group(v-show="choosePlan.name")
                        cell(title="运费", :value="0 | currency('￥')")
                        cell(title="商品租金", :value="0 | currency('￥')")
                        cell(title="优惠券", :is-link="true", disabled)
                            span(slot="default", style="color:#999999") 暂无可用
                        cell(title="实际押金", :value="0 | currency('￥')")
                            span(slot="inline-desc", style="color:blue", @click="goAuthInfo()", v-if="zmScore==0") 芝麻信用可减免押金,去授权
                            span(slot="inline-desc", style="color:red", @click="goAuthInfo()", v-else) 平台已为您减免0.00元押金
                    group(v-show="!choosePlan.name")
                        cell(title="运费", :value="freight | currency('￥')")
                        cell(title="商品租金", :value="rent_price | currency('￥')")
                        cell(title="优惠券", :is-link="true",@click.native="cardshow(1)")
                            span(slot="default", style="color:#999999",v-show="currentPrice-0 ==0") {{this.zjList.length == 0 ? '暂无可用' : this.zjList.length + '张可用'}}
                            span(slot="default",v-show="currentPrice-0 !=0") {{currentPrice | currency('￥')}}
                        <div v-transfer-dom>
                            <popup style="border-top:1px solid #eee;background:#fff;z-index:99999 ;overflow:hidden" v-model="cardShow" position="bottom" max-height="60%">
                                <ul style="box-sizing:border-box;padding-bottom:60px;max-height:500px;overflow-y:auto;" class="card_main_list">
                                    <li class="card_main_single" v-for="item in cardList" @click="goShop(item)">
                                        <img src="~@/assets/img/common/cardbg.png" alt="card">
                                        <div class="card_main_single_box">
                                            <div class="card_main_single_left">
                                                <h3 class="card_main_single_price">￥
                                                    <span>{{item.amount}}</span>
                                                </h3>
                                                <template v-if="item.use_range==1">
                                                    <h5 class="card_main_single_rules">全平台可用</h5>
                                                </template>
                                                <template v-else>
                                                    <h5 class="card_main_single_rules">指定店铺可用</h5>
                                                </template>
                                            </div>
                                            <div class="card_main_single_right">
                                                <template v-if="item.use_range==1">
                                                    <h3 class="card_main_single_title">租介红包</h3>
                                                </template>
                                                <template v-else>
                                                    <h3 class="card_main_single_title">店铺红包</h3>
                                                    <h3 class="card_main_single_store">{{item.store_name}}</h3>
                                                </template>
                                                <p class="card_main_single_time nowarp">使用期限：{{item.use_start_time | dataform}}-{{item.use_end_time | dataform}}</p>
                                                <button class="card_main_single_btn" type="button">去使用</button>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                                <button class="orderInfon_main_cardclose" type="button" @click="closeCard">不使用优惠券</button>
                            </popup>
                        </div>
                        cell(title="实际押金", :value="deposit * antDerate | currency('￥')")
                            span(slot="inline-desc", style="color:blue", @click="goAuthInfo()", v-if="zmScore==0") 芝麻信用可减免押金,去授权
                            span(slot="inline-desc", style="color:red", @click="goAuthInfo()", v-else) 平台已为您减免{{deposit - deposit * antDerate}}元押金
                    //-- 收货地址和物流方式 -->
                    group.orderInfon_main_priceColl
                        x-textarea(:max="20", v-model="option", placeholder="买家留言")

            footer.orderInfon_footer
                div.orderInfon_footer_price(v-show="choosePlan.id") 合计：
                    span {{localdata.data.length}}本
                button(@click="buygoods", type="button",v-show="canPay && choosePlan.id").orderInfon_footer_btn 借阅
                button(type="button",v-show="!canPay && !choosePlan.id").orderInfon_footer_noControl 暂不支持该地区
                div.orderInfon_footer_price(v-show="!choosePlan.id")
                    div 合计：
                        span {{goodsTotolPrice | currency('￥')}}
                    p 押金可退：{{deposit * antDerate | currency('￥')}}
                button.orderInfon_footer_btn(@click="buygoods", type="button", v-show="canPay && !choosePlan.id") 提交订单
                button(type="button",v-show="!canPay && !choosePlan.id").orderInfon_footer_noControl 暂不支持该地区
            toast(v-model="toast",type="success")  {{confrim}}
</template>
<script>
import { XHeader, Cell, Group, XTextarea, dateFormat, Toast,TransferDom, CellBox, Popup } from 'vux';
import { mapGetters } from 'vuex'
import { API, getQuery } from '../../../services';
import HeaderCop from '../common/header.vue';
import BScroll from '../common/scrollView.vue';
export default {    
    directives: {
        TransferDom
    },
    components: {
        XHeader,
        Group,
        Cell,
        XTextarea,
        Toast,
        CellBox,
        BScroll,
        HeaderCop,
        Popup,
    },
    data() {
        return {
            canPay:true,
            confrim: "请选择地址",
            /* 提示信息 */
            toast: false,
            orderLogistics: '/orderLogistics/',
            /* 是否拥有默认数据 */
            haveDefault: false,
            /* 订单详情数据 */
            localdata: {
                data:[]
            },
            /* 买家留言 */
            option: "",
            title:"订单详情",
            choosePlan:{},
            service_area:"", //支持的地址,
            freight: 0, //运费
            rent_price: 0, //租金
            deposit: 0, //押金
            zmScore: 0, //信用分
            goodsTotolPrice: 0, //合计金额
            antDerate: 1,
            planCount: 0,
            currentPrice: 0, //优惠金额
            cardList: [],
            zjList: [],
            cardShow: false,
            cardstate: {
                id: "",//平台红包
                storeId: "",//店铺红包
            },
            currentCardType: 0,
        }
    },
    computed: {
        ...mapGetters([
            'getUserInfoUserId',
            'getUserInfoToken',
            'getAddress',
            'getNamePhone'
        ]),
        /* 返回初始和结束周期 */
        rentRange() {
            let self = this;
            let start = this.localdata.time;
            let num = 1;
            /* 获取日月季 */
            let year = new Date(start).getFullYear(),
                month = new Date(start).getMonth() + 1,
                /* 当前天数 */
                day = new Date(start).getDate(),
                /* 获取当前时间数（毫秒） */
                time = new Date(start).getTime();
            let year_3 = Math.floor((month + num) / 12);
            let month_3 = (month + num) % 12;
            if (month_3 == 0) {
                month_3 = 12;
                year_3--;
            }
            let monthTime=new Date(year + year_3 + "/" + month_3 + "/" +day).getTime();
            let end =dateFormat(monthTime-24 * 3600 * 1000, 'YYYY-MM-DD');
            return { start, end };
        },
    },
    methods: {
        /* 优惠券选择 */
        cardshow(type) {
            this.currentCardType = type;
            type == 1 ? this.cardList = this.zjList : this.cardList = this.storeList;
            if (this.cardList.length == 0) {
                this.confrim = "暂无可用红包";
                this.toast = true;
                return false;
            }
            this.cardShow = true;
        },        
        getCardList() {
            /* 平台红包 */
            API.card.storeCard({
                userId: this.getUserInfoUserId,
                token: this.getUserInfoToken,
                goods_type: 1,
                type: 1
            }).then((res) => {
                if (res.body.code == 200) {
                    this.zjList = res.body.data;
                }
            });
        },
        delItem(index){
            let self = this;
            this.$vux.confirm.show({
                /* title: 'Title', */
                content: '确定删除该绘本',
                onConfirm() {
                    /* 点击确认时执行具体删除操作 */
                   self.localdata.data.splice(index,1); 
                   if(self.localdata.data.length==0){
                       self.routerBack();
                   }
                }
            });
            
        },
        /* 选择完成 */
        goShop(item) {
            /* 当前数据类型为店铺红包 */
            if (this.currentCardType == 0) {
                this.cardstate.storeId = item.coupon_no;
                this.storePrice = 0 - item.amount;
                if (this.storePrice + this.goodsAllPrice <= 0) {
                    this.storePrice = 0 - this.goodsAllPrice;
                }
                /* 平台红包已经选择的情况下 */
                if (this.currentPrice != 0) {
                    if (this.storePrice + this.goodsAllPrice == 0) {
                        this.currentPrice = 0;
                        this.cardstate.id = "";
                    } else {
                        this.currentPrice = 0 - (this.goodsAllPrice + this.storePrice);
                    }
                }
            } else {
                if (this.storePrice + this.goodsAllPrice == 0) {
                    this.confrim = "已达最大优惠额度";
                    this.toast = true;
                    this.cardShow = false;
                    return false;
                } else {
                    this.cardstate.id = item.coupon_no;
                    this.currentPrice = 0 - item.amount;
                    if (this.currentPrice + this.storePrice + this.goodsAllPrice <= 0) {
                        this.currentPrice = 0 - (this.goodsAllPrice + this.storePrice);
                    }
                }
            }
            /* 当前优惠价格 */
            let allPrice = this.rent_price + this.currentPrice;
            allPrice = (allPrice <= 0 ? 0 : allPrice);
            this.goodsTotolPrice =  allPrice + this.freight + (this.deposit * this.antDerate);
            this.priceShow = true;
            this.cardShow = false;
        },
        /* 关闭红包选择框 */
        closeCard() {
            /* 撤销店铺红包 */
            if (this.currentCardType == 0) {
                /* 存在平台红包的情况下 */
                if (this.currentPrice != 0) {
                    if (this.currentPrice + this.goodsAllPrice <= 0) {
                        this.currentPrice = 0 - this.goodsAllPrice;
                    } else {
                        for (let item of this.zjList) {
                            if (item.coupon_no == this.cardstate.id) {
                                this.currentPrice = 0 - item.amount;
                            }
                        }
                    }
                }
                this.storePrice = 0;
                this.cardstate.storeId = "";
            } else {
                this.cardstate.id = "";
                this.currentPrice = 0;
            }
            let allPrice = this.rent_price + this.currentPrice;
            allPrice = (allPrice <= 0 ? 0 : allPrice);
            this.goodsTotolPrice =  allPrice + this.freight + (this.deposit * this.antDerate);
            this.cardShow = false;
        },
        goAuthInfo(){
            this.$router.push({
                path:"/authInfo"
            })  
        },
        /* 滚动列表重置刷新 */
        scollRefresh(){
            /* this.$refs.scollView.scroll.refresh(); */
        },
        routerBack() {
            this.$router.goBack();
        },
        userZMScore() {
            API.person.getUserZMScore({
                user_id: this.getUserInfoUserId
            }).then((res) => {
                if (res.body.code == 200) {
                    if(res.body.msg == "获取成功"){
                        this.zmScore = res.body.data.zmscore;
                    }
                }
            })
            if((650 < this.zmScore) && (this.zmScore <= 700)) {
                this.antDerate = 0.8
            }else if((701 < this.zmScore) && (this.zmScore <= 750)) {
                this.antDerate = 0.7
            }else if((751 < this.zmScore) && (this.zmScore <= 800)) {
                this.antDerate = 0.6
            }else if(800 < this.zmScore) {
                this.antDerate = 0.5
            }
        },
        /* 提交订单 */
        buygoods() {
            /* 数值校验 */
            if (this.getAddress == "") {
                this.confrim = "请选择地址";
                this.toast = true;
                return false;
            }
            let self = this;
            let book_ids=[];
            for (const item of this.localdata.data) {
                book_ids.push(item.book_id);
            }
            if (!this.choosePlan.id) {
                API.book.createBookOnceOrder({
                    address_id:self.$store.state.addressData.id||self.$store.state.addressData.address_id,
                    user_id: self.getUserInfoUserId,
                    token: self.getUserInfoToken,
                    rent_price: this.rent_price,
                    deposit: this.deposit * this.antDerate,
                    coupon_no: this.cardstate.id,
                    freight: this.freight,
                    books: book_ids,
                    start_date: self.rentRange.start,
                    end_date: self.rentRange.end,
                    message: self.option,
                }).then((res) => {
                    // console.log(res)
                    if(res.body.code==200){
                        API.book.H5Pay({
                            userId: self.getUserInfoUserId,
                            token: self.getUserInfoToken,
                            orderSn: res.body.data.order_sn,
                            payMethod: 3,
                            type: 1,
                        }).then((res) => {
                            const div = document.createElement('div');
                            div.innerHTML = res.data;
                            document.body.appendChild(div);
                            document.forms[0].submit();
                        })
                    }else{
                        self.confrim = res.body.msg;
                        self.toast = true;
                        return false;
                    }
                })
            }else {
                API.book.createOrder({
                    user_id: self.getUserInfoUserId,
                    token: self.getUserInfoToken,   
                    address_id:self.$store.state.addressData.id||self.$store.state.addressData.address_id,
                    card_id:self.choosePlan.id,
                    start_date:self.rentRange.start,
                    end_date:self.rentRange.end,
                    books:book_ids,
                    message:self.option,
                }).then((res)=>{
                    if(res.body.code==200){
                        self.$router.push({
                            path:"/book_bookSuccess"
                        })  
                    }else{
                        self.confrim = res.body.msg;
                        self.toast = true;
                        return false;
                    }
                })
            }
        },
        /* 数据初始化 */
        Initialization() {
            this.getDefaultAddress();
            this.getCardList();
        },
        noPlan() {
            let book_ids=[];
            for (const item of this.localdata.data) {
                book_ids.push(item.book_id);
            }
            API.book.getPurchasePackage({
                books: book_ids
            }).then((res) => {
                this.deposit = res.body.data.deposit;
                this.freight = res.body.data.freight;
                this.rent_price = res.body.data.rent_price;
                let allPrice = this.rent_price + this.currentPrice;
                allPrice = (allPrice <= 0 ? 0 : allPrice);
                this.goodsTotolPrice =  allPrice + this.freight + (this.deposit * this.antDerate);
            });
        },
        /* 获取用户默认地址，并且出发vuex更新 */
        getDefaultAddress() {
            API.person.getAddressList({
                userId: this.getUserInfoUserId,
                token: this.getUserInfoToken,
            }).then((res) => {
                if (res.body.code == 200) {
                    for(let key in res.body.data.addressList.data){
                        if(res.body.data.addressList.data[key]['is_set_default'] === 1) {
                            this.haveDefault = true;
                            this.$store.dispatch('SetAddress', res.body.data.addressList.data[key]);
                        }
                    }
                }
            });
            API.book.defaultAddress({
                user_id: this.getUserInfoUserId,
                token: this.getUserInfoToken,
            }).then((res) => {
                if (res.body.code == 200) {
                    this.service_area=res.body.data.service_area;
                }
            });
        },

    }, mounted() {
        this.Initialization();
        
    },
    activated() {
        this.userZMScore()
        /* 地址点击函数 */
        if (localStorage.getItem('addressClick')) {
            localStorage.setItem('addressClick', '');
            API.book.checkAddress({
                user_id: this.getUserInfoUserId,
                token: this.getUserInfoToken,
                address_id:this.$store.state.addressData.id||this.$store.state.addressData.address_id
            }).then((res) => {
                if (res.body.code != 200) {
                   this.confrim=res.body.msg;
                   this.canPay=false;
                   this.toast=true;
                }else{
                   this.canPay=true; 
                }
            });
            this.haveDefault = true;
        }
        /* 获取当前数据 */
        this.localdata=JSON.parse(localStorage.getItem("bookOrder"));
        this.choosePlan={};
        let  choosePlan=localStorage.getItem("choosePlan");
        if(choosePlan){
            if(choosePlan != 'none'){
                this.choosePlan=JSON.parse(choosePlan);
            }else {
                this.noPlan();
            }
        }else{
            API.book.myValidCards({
                user_id: this.getUserInfoUserId,
                token: this.getUserInfoToken,
                book_num:this.localdata.data.length,
            }).then((res) => {
               if(res.body.code==200){
                    this.planCount = res.body.data.length;
                    if(res.body.data.length>=1){
                        this.choosePlan={
                            name:res.body.data[0].name,
                            id:res.body.data[0].user_card_id
                        }
                    }else{
                        this.noPlan();
                    }
                 }
            })
        }

        
    }
} 
</script>